import md5 = require("md5");
import crypto = require("crypto");

// DES 解密
function desDecrypt(text, key = 'YusupTurak') {
    key = key.length >= 8 ? key.slice(0, 8) : key.concat('0'.repeat(8 - key.length))
    const keyHex = Buffer.from(key)
    const cipher = crypto.createDecipheriv('des-cbc', keyHex, keyHex)
    let c = cipher.update(text, 'base64', 'utf8')
    c += cipher.final('utf8')
    return c
}
export default (_options, app) => {
    return async function csrfToken(ctx, next) {

        /* console.log(ctx.response.status);
        if (ctx.response.status === 404) {
            ctx.body = `<div class="wrapper"><h1>404 Not Found</h1><div class="wechat">微信：Yusup0604</div><img src="/public/images/mywechat2.png"/></div><style>h1{font-size: 6vw;color:#ffffff}\nbody,html,h1{margin:0;padding:0;}\nbody{background: linear-gradient(to right, #b993d6, #8ca6db);}\n.wrapper,body{display:flex;justify-content:center;align-items:center;}\n.wrapper{flex-direction: column;}\n.wechat {margin-bottom:16px;font-size:4vw;color:#ffffff}\nimg{width:24vw;}</style>`;
            ctx.status = 404
            await next();
        } else { */
        //? 后台跳过鉴权 
        if (ctx.url.includes('/admin/')) {
            let { ts } = ctx.header;
            let system = ctx.header['user-agent']
            let csrfTokenCode = ctx.headers['csrftoken'];
            let { Joi } = app;
            let schema = Joi.object({
                ts: Joi.number().required(),
                system: Joi.string().required(),
                csrfTokenCode: Joi.string().required()
            });
            let { error } = ctx.validate(schema, { ts, csrfTokenCode, system });
            if (error) {
                ctx.status = 403;
                ctx.body = '非法请求'
            } else {
                if (ctx.url.includes('/admin/user/login')) {
                    app.dbName = 'Yusup'
                    await next();
                } else {
                    let userName = ctx.headers['x-user'];

                    if (!userName) {
                        ctx.status = 403;
                        ctx.body = '非法请求'
                        return;
                    } else {
                        app.dbName = userName || 'Yusup'
                    }
                    let user_token = ctx.cookies.get("user_token", {
                        encrypt: false,
                        signed: false
                    }) as string;
                    user_token = desDecrypt(user_token);
                    let password = ctx.headers['x-token']
                    let [tempToken, timeStamp] = user_token.split(/(\d{13})$/);

                    if ((Date.now() - Number(timeStamp) > 24 * 60 * 60 * 1000) || tempToken != password) {
                        ctx.data = {
                            code: 401 //未登录
                        }
                    } else {
                        await next();
                    }
                    // let serverCsrfToken = md5(`${Number(ts)}-${system}-${Number(ts).toString(36)}`);
                    // if (csrfTokenCode !== serverCsrfToken || Date.now() - ts > 10000) {
                    //     ctx.status = 416;
                    //     ctx.body = '请求无效'
                    // } else {
                    //     await next();
                    // }
                }
            }
        }
        //? APP 
        else if (ctx.url.includes('/app/')) {
            let { ts, system } = ctx.header;
            let csrfTokenCode = ctx.header['csrf-token'];
            let appName = ctx.header['x-user'];
            if (!appName) {
                ctx.status = 403;
                ctx.body = '非法请求'
                return;
            } else {
                app.dbName = appName
            }
            let { Joi } = app;
            let schema = Joi.object({
                ts: Joi.number().required(),
                system: Joi.string().required(),
                csrfTokenCode: Joi.string().required()
            });
            let { error } = ctx.validate(schema, { ts, csrfTokenCode, system });
            if (error) {
                ctx.status = 403;
                ctx.body = '非法请求'
            } else {
                let serverCsrfToken = md5(`${Number(ts)}-${system}-${Number(ts).toString(36)}`);
                if (csrfTokenCode !== serverCsrfToken || Date.now() - ts > 10000) {
                    ctx.status = 416;
                    ctx.body = '请求无效'
                } else {
                    await next();
                }
            }
        }
        else {
            ctx.body = `<style>img{width:50vw;}</style><div class="wrapper"><h1>404 Not Found</h1><div class="wechat">微信：Coder_Yusup</div><img src="https://cdn.qolayapp.cn/statics/images/myWechat.webp"/></div><style>h1{font-size: 6vw;color:#ffffff}\nbody,html,h1{margin:0;padding:0;}\nbody{background: linear-gradient(to right, #b993d6, #8ca6db);}\n.wrapper,body{display:flex;justify-content:center;align-items:center;}\n.wrapper{flex-direction: column;}\n.wechat {margin-bottom:16px;font-size:4vw;color:#ffffff}\n}</style>`;
            ctx.status = 404
            // await next();
            // await next();
        }
    }
    // }
};